<template>
  <Teleport to="body">
    <!-- 遮罩层 -->
    <div
      v-if="modelValue || isLeaving"
      class="v-popup-mask"
      :class="{ 'mask-active': modelValue && !isLeaving }"
      @click.self="handleMaskClick"
    ></div>

    <!-- 弹窗容器 -->
    <div
      v-if="modelValue || isLeaving"
      class="v-popup-wrapper"
      :class="{
        'dialog-active': modelValue && !isLeaving,
        'dialog-leave': isLeaving
      }"
      :style="wrapperStyle"
    >
      <div class="v-popup-container">
        <!-- 弹窗头部 -->
        <div class="v-popup-header">
          <div class="v-popup-title">
            <i v-if="icon" :class="['iconfont', icon]"></i>
            <span>{{ title }}</span>
          </div>
          <button class="v-popup-close" @click="handleClose">
            <i class="iconfont icon-close"></i>
          </button>
        </div>

        <!-- 弹窗内容区域 -->
        <div class="v-popup-body">
          <slot></slot>
        </div>

        <!-- 弹窗底部按钮 -->
        <div v-if="showFooter" class="v-popup-footer">
          <button class="cancel-btn" @click="handleClose">取消</button>
          <button
            class="confirm-btn"
            @click="handleConfirm"
            :disabled="confirmLoading"
          >
            <i v-if="confirmLoading" class="iconfont icon-loading spin"></i>
            {{ confirmText }}
          </button>
        </div>
      </div>
    </div>
  </Teleport>
</template>

<script>
export default {
  name: "vPopup",
  props: {
    modelValue: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: "提示",
    },
    width: {
      type: String,
      default: "600px",
    },
    icon: {
      type: String,
      default: "",
    },
    showFooter: {
      type: Boolean,
      default: true,
    },
    closeOnClickMask: {
      type: Boolean,
      default: true,
    },
    confirmText: {
      type: String,
      default: "确认",
    },
    asyncConfirm: {
      type: Boolean,
      default: false,
    },
    customStyles: {
      type: Object,
      default: () => ({})
    },
    keepOpenOnError: {
      type: Boolean,
      default: false,
    },
    keepOpenAfterConfirm: {
      type: Boolean,
      default: false,
    }
  },
  emits: ['update:modelValue', 'confirm', 'close'],
  data() {
    return {
      confirmLoading: false,
      isLeaving: false
    };
  },
  computed: {
    wrapperStyle() {
      // 合并基础样式和自定义样式
      return {
        minWidth: this.width,
        maxWidth: this.width,
        ...this.customStyles
      };
    }
  },
  methods: {
    handleClose() {
      if (this.isLeaving) return;
      this.startLeaveAnimation();
      this.$emit('close');
    },
    async handleConfirm() {
      if (this.asyncConfirm) {
        this.confirmLoading = true;
        try {
          // 创建一个Promise来处理确认事件
          const confirmResult = new Promise((resolve, reject) => {
            // 在Vue 3中获取确认事件处理函数
            // 方法1：通过vnode props获取
            let originalConfirmHandler;
            
            // 尝试获取确认事件处理函数的几种方式
            if (this.$ && this.$.vnode && this.$.vnode.props && this.$.vnode.props['onConfirm']) {
              originalConfirmHandler = this.$.vnode.props['onConfirm'];
            } else if (this.$listeners && this.$listeners.confirm) {
              // 兼容Vue 2的方式（如果仍被支持）
              originalConfirmHandler = this.$listeners.confirm;
            }
            
            if (originalConfirmHandler) {
              try {
                // 调用原始的确认事件处理函数
                const result = originalConfirmHandler.call(this);
                // 检查返回值是否为Promise
                if (result && typeof result.then === 'function') {
                  result.then(resolve).catch(reject);
                } else {
                  resolve(result);
                }
              } catch (error) {
                reject(error);
              }
            } else {
              // 如果没有找到确认事件处理函数，直接触发confirm事件
              this.$emit('confirm');
              resolve();
            }
          });
          
          await confirmResult;
          // 如果没有设置keepOpenAfterConfirm为true，则确认成功后关闭弹窗
          if (!this.keepOpenAfterConfirm) {
            this.startLeaveAnimation();
          }
        } catch (error) {
          // 如果设置了keepOpenOnError为true，则在错误时不关闭弹窗
          if (!this.keepOpenOnError && !this.keepOpenAfterConfirm) {
            this.startLeaveAnimation();
          }
          // 重新抛出错误，让上层组件可以捕获
          throw error;
        } finally {
          this.confirmLoading = false;
        }
      } else {
        this.$emit('confirm');
        // 如果没有设置keepOpenAfterConfirm为true，则确认后关闭弹窗
        if (!this.keepOpenAfterConfirm) {
          this.startLeaveAnimation();
        }
      }
    },
    handleMaskClick() {
      if (this.closeOnClickMask) {
        this.handleClose();
      }
    },
    startLeaveAnimation() {
      this.isLeaving = true;
      setTimeout(() => {
        this.$emit('update:modelValue', false);
        this.isLeaving = false;
      }, 300);
    }
  },
};
</script>

<style scoped lang="less">
/* 遮罩层 */
.v-popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(64, 81, 137, 0.25);
  transition: opacity 0.3s ease-in-out;
  z-index: 1000;
  opacity: 0;
}

.v-popup-mask.mask-active {
  opacity: 1;
}

/* 弹窗容器 */
.v-popup-wrapper {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%) translateY(-20px);
  opacity: 0;
  border-radius: 8px;
  min-width: 300px;
  max-width: 80%;
  z-index: 1001;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  will-change: transform, opacity;
  box-shadow: rgba(0, 0, 0, 0.1) 0px 4px 12px;
  border: rgba(255, 255, 255, 0.3) 6px solid;
  box-sizing: content-box;
}

/* 表单两列布局样式支持 - 通过CSS变量实现跨组件样式共享 */
.v-popup-wrapper {
  & .vForm {
    padding: var(--form-padding, 0 20px);
    width: var(--form-row-width, 100%);
  }
  
  & .vForm .form-row {
    display: var(--form-row-display, block);
    gap: var(--form-row-gap, 0);
    margin-bottom: 16px;
    width: var(--form-row-width, 100%);
  }
  
  & .vForm .form-group.half-width {
    width: var(--form-half-width, 100%);
    box-sizing: border-box;
  }
  
  & .vForm .form-group {
    display: var(--form-group-display, block);
    flex-direction: var(--form-group-direction, column);
    margin-bottom: 0;
  }
  
  & .vForm .form-input {
    width: 100%;
    box-sizing: border-box;
  }
}

.v-popup-container {
  background: var(--v-card-bg);
  border-radius: 8px;
  width: 100%;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

.v-popup-wrapper.dialog-active {
  transform: translate(-50%, -50%) translateY(0);
  opacity: 1;
}

.v-popup-wrapper.dialog-leave {
  transform: translate(-50%, -50%) translateY(-20px);
  opacity: 0;
  transition: all 0.2s ease-in;
}

/* 弹窗头部 */
.v-popup-header {
  padding: 16px 24px;
  border-bottom: 1px solid var(--v-border-color);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.v-popup-title {
  font-size: 18px;
  font-weight: 600;
  color: #1a2b50;
  display: flex;
  align-items: center;
  
  .iconfont {
    margin-right: 8px;
    color: var(--v-theme);
    font-size: 20px;
  }
}

.v-popup-close {
    background: var(--v-background-pure);
    border: 1px solid var(--v-border-color);
    color: var(--v-text-light);
    cursor: pointer;
    font-size: 16px;
    width: 32px;
    height: 32px;
    min-width: 32px;
    padding: 0;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    /* 完全重置按钮默认样式 */
    outline: none;
    font-family: inherit;
    margin: 0;
    text-decoration: none;
    overflow: visible;
    text-transform: none;
    -webkit-appearance: button;
    line-height: 1;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    
    &:hover {
      color: var(--v-danger);
      background-color: rgba(234, 84, 85, 0.05);
      border-color: var(--v-danger);
      transform: translateY(-1px);
      box-shadow: 0 4px 8px rgba(234, 84, 85, 0.1);
    }
    
    &:active {
      transform: translateY(0);
    }
    
    .iconfont {
      font-size: 14px;
    }
  }

/* 弹窗内容区域 */
.v-popup-body {
  padding: 24px;
  // overflow-y: auto;
  flex: 1;
  color: var(--v-text);
  font-size: 14px;
  line-height: 1.5;
}

/* 弹窗底部按钮 */
.v-popup-footer {
  padding: 16px 24px;
  border-top: 1px solid var(--v-border-color);
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
  min-width: 80px;
  height: 36px;
  font-weight: 500;
}

.cancel-btn {
  background-color: #f0f0f0;
  color: var(--v-text);
  
  &:hover {
    background-color: #e0e0e0;
    transform: translateY(-1px);
  }
  
  &:active {
    transform: translateY(0);
  }
}

.confirm-btn {
  background-color: var(--v-theme);
  color: white;
  position: relative;
  overflow: hidden;
  
  &:hover {
    filter: brightness(0.9);
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  }
  
  &:active {
    transform: translateY(0);
  }
  
  &[disabled] {
    background-color: #ccc;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
  }
  
  .iconfont {
    margin-right: 4px;
  }
}

/* 加载动画 */
.spin {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 自定义动画 - 用于按钮点击效果 */
@keyframes ripple {
  0% {
    transform: scale(0);
    opacity: 0.8;
  }
  100% {
    transform: scale(2);
    opacity: 0;
  }
}

/* 图标颜色优化 */
.icon-success {
  color: var(--v-success) !important;
}

.icon-error {
  color: var(--v-danger) !important;
}

.icon-warning,
.icon-alert {
  color: var(--v-warning) !important;
}

.icon-info {
  color: var(--v-theme) !important;
}
</style>